/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import <UIKit/UIKit.h>
#import "ContactsSettingsView.h"
#import "UIController.h"
#import "FunambolAPI.h"
#import "FastSyncMethodsView.h"

#import "customs.h"

@implementation ContactsSettingsView

- (BOOL) isPathEnabled{
    return false;
}

- (id) init {
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"Contacts",@"Contacts");
		menuList = [[NSMutableArray alloc] init];
	}
    funBlue = [[UIColor alloc] initWithRed:0.0 green:0.4 blue:0.9 alpha:1.0];
	return self;
}    
    
- (void) loadView{
    
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
    
    FastSyncMethodsView* syncmethodsview = [[FastSyncMethodsView alloc] init];
    NSString * mode = [[FunambolAPI getInstance] getSync:@"addressbook"];
    [syncmethodsview setSyncSourceName:@"addressbook"];
    [syncmethodsview setSyncMode:mode];

    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Sync Methods", @""), @"title",
                         syncmethodsview, @"viewController",
                         nil]];
	[syncmethodsview release];
	
	self.view.autoresizesSubviews = YES;

    small_font = [UIFont systemFontOfSize:15];
    
    syncValue = [[FunambolAPI getInstance] getSync:@"addressbook"];
    remoteURIValue = [[FunambolAPI getInstance] getURI:@"addressbook"];
        
    contactsTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
	contactsTable.delegate = self;
    contactsTable.dataSource = self;
	contactsTable.rowHeight = 40;
    [contactsTable reloadData];
    
    [self.view addSubview:contactsTable];
    
    contactSyncCell     =   [[UITableViewCell alloc]init];
    syncWayCell         =   [[UITableViewCell alloc]init];
    pathCell            =   [[UITableViewCell alloc]init];
    remoteURICell       =   [[UITableViewCell alloc]init];
    
    path          =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [path addTarget:self action:@selector(pathAction:) forControlEvents:UIControlEventValueChanged];

    [[pathCell textLabel] setText:NSLocalizedString(@"Sync", @"Sync")];
    [pathCell addSubview:path];
    
    contactSync       =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [contactSync addTarget:self action:@selector(contactSyncAction:) forControlEvents:UIControlEventValueChanged];
    if([mode isEqualToString:@"none"]){
        [contactSync setOn:NO animated:NO];
    }else{
        [contactSync setOn:YES animated:NO];
    }
    
    [[contactSyncCell textLabel] setText:NSLocalizedString(@"Sync", @"Sync")];
    [contactSyncCell addSubview:contactSync];
    
    [syncWayCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [[syncWayCell textLabel] setText:NSLocalizedString(@"Sync Direction",@"Sync Direction")];
    syncWayLabel = [[UILabel alloc] initWithFrame:CGRectMake(140.0, 7.0, 140.0, 25.0)];
    if([syncValue isEqualToString:@"two-way"]){
        [syncWayLabel setText:NSLocalizedString(@"Two Way",@"Two Way")];
    }else if([syncValue isEqualToString:@"one-way-from-client"]){
        [syncWayLabel setText:NSLocalizedString(@"From Client",@"From Client")];
    }else if([syncValue isEqualToString:@"one-way-from-server"]){
        [syncWayLabel setText:NSLocalizedString(@"From Server",@"From Server")];
    }else if([syncValue isEqualToString:@"none"]){
        [syncWayLabel setText:NSLocalizedString(@"Disabled",@"Disabled")];
    }
    [syncWayLabel setTextColor:funBlue];
    [syncWayLabel setFont:small_font];
    [syncWayLabel setTextAlignment:UITextAlignmentRight];
    
    [syncWayCell addSubview:syncWayLabel];
    
    
    remoteURI = [[UITextField alloc] initWithFrame:CGRectMake(140.0,11.0, 160.0, 25.0)];
    remoteURI.borderStyle = UITextBorderStyleNone;
    remoteURI.textColor = funBlue;
    remoteURI.font = small_font;
    [remoteURI setTextAlignment:UITextAlignmentRight];
    remoteURI.autocorrectionType = UITextAutocorrectionTypeNo;
    remoteURI.text=remoteURIValue;
    remoteURI.backgroundColor = [UIColor whiteColor];
    remoteURI.keyboardType = UIKeyboardTypeDefault;
    remoteURI.returnKeyType = UIReturnKeyDone;
    remoteURI.clearButtonMode = UITextFieldViewModeNever;
    [remoteURI addTarget:self action:@selector(remoteURIAction:) forControlEvents:UIControlEventAllEditingEvents];
    [[remoteURICell textLabel] setText:NSLocalizedString(@"Remote URI", @"Remote URI")];
    [remoteURICell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [remoteURICell addSubview:remoteURI];
    

    companyDirectory      =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [companyDirectory     addTarget:self action:@selector(companyDirectoryAction:) forControlEvents:UIControlEventValueChanged];
    [companyDirectory     setOn:(
                            ([remoteURI.text length] >= [@"-shared" length])
                            &&
                                ([
                                    [remoteURI.text substringFromIndex:
                                        ([remoteURI.text length] - ([@"-shared" length]))]
                                compare:@"-shared"]
                                 == 0)
                            )
                          animated:NO];
    
    companyDirectoryCell  =   [[UITableViewCell alloc]init];
    [[companyDirectoryCell textLabel] setText:NSLocalizedString(@"Company Directory", @"Company Directory")];
    [companyDirectoryCell addSubview:companyDirectory];   
    if (CUSTOM_CONTACTS_COMPANY_DIRECTORY) { // BEGIN CUSTOM
        remoteURI.enabled = false;
        remoteURI.textColor = [UIColor grayColor];
    } // END CUSTOM
    [mode release];
}



//TABLE VIEW

- (UITableViewCell *)tableView:(UITableView *)contactsTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
#ifndef FUNAMBOL_APP_STORE
        switch (indexPath.section) {
            case 0:
                switch (indexPath.row) {
                    case 0:
                        return contactSyncCell;
                    default:
                        break;
                }
                break;
            case 1:
                switch (indexPath.row) {
                    case 0:
                        return syncWayCell;
                    default:
                        break;
                }
                break;
            case 2:
            {
                if ([self isPathEnabled]){
                    switch (indexPath.row) {
                        case 0:
                            return pathCell;
                        case 1:
                            return remoteURICell;
                        default:
                            break;
                    }
                }else{
                    switch (indexPath.row) {
                        case 0:
                            return remoteURICell;
                        default:
                            break;
                    }
                }
                
                // This will always be last, so we dont need more switches
                if (CUSTOM_CONTACTS_COMPANY_DIRECTORY) { // BEGIN CUSTOM
                    return companyDirectoryCell;
                } // END CUSTOM
            }
                break;
            default:
                break;
        }
#else
        switch (indexPath.section) {
            case 0:
                switch (indexPath.row) {
                    case 0:
                        return syncWayCell;
                    default:
                        break;
                }
                break;
            case 1:
            {
                if ([self isPathEnabled]){
                    switch (indexPath.row) {
                        case 0:
                            return pathCell;
                        case 1:
                            return remoteURICell;
                        default:
                            break;
                    }
                }else{
                    switch (indexPath.row) {
                        case 0:
                            return remoteURICell;
                        default:
                            break;
                    }
                }
            
                // This will always be last, so we dont need more switches
                if (CUSTOM_CONTACTS_COMPANY_DIRECTORY) { // BEGIN CUSTOM
                    return companyDirectoryCell;
                } // END CUSTOM
            }
                break;
            default:
                break;
        }
#endif
    
    return nil;
}

- (void)tableView:(UITableView *)contactsTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
#ifndef FUNAMBOL_APP_STORE
        switch (indexPath.section) {
            case 1:
                switch (indexPath.row) {
                    case 0:
                        if([contactSync isOn]){
                            UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                            NSString * mode = [[FunambolAPI getInstance] getSync:@"addressbook"];
                            [((SyncMethodsView*)targetViewController) setSyncMode:mode];
                            [mode release];
                            [[self navigationController] pushViewController:targetViewController animated:YES];
                        }
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
#else
        switch (indexPath.section) {
            case 0:
                switch (indexPath.row) {
                    case 0:
                        UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                        NSString * mode = [[FunambolAPI getInstance] getSync:@"addressbook"];
                        [((SyncMethodsView*)targetViewController) setSyncMode:mode];
                        [mode release];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
#endif


}

- (NSInteger)tableView:(UITableView *)contactsTable numberOfRowsInSection:(NSInteger)section {
#ifndef FUNAMBOL_APP_STORE
        switch (section) {
            case 0:
                return 1;
            case 1:
                return 1;
            case 2:
                {
                    int size = 1;
                    if (CUSTOM_CONTACTS_COMPANY_DIRECTORY) { // BEGIN CUSTOM
                        size++;
                    } // END CUSTOM
                    if ([self isPathEnabled]) {
                        size++;
                    }
                    return size;
                }
                break;
            default:
                break;
        }
#else
        switch (section) {
            case 0:
                return 1;
            case 1:
                {
                    int size = 1;
                    if (CUSTOM_CONTACTS_COMPANY_DIRECTORY) { // BEGIN CUSTOM
                        size++;
                    } // END CUSTOM
                    if ([self isPathEnabled]) {
                        size++;
                    }
                    return size;
                }
                break;
            default:
                break;
            }         
#endif
    return 0;//should never happen
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)contactsTable {
#ifndef FUNAMBOL_APP_STORE
        return 3;
#else
        return 2;
#endif
}

- (void) pathAction: (id)sender{
    
}

- (void) remoteURIAction: (id)sender{
    
    [[FunambolAPI getInstance] setURI:remoteURI.text syncsourcename:@"addressbook"];
    
}

- (void) contactSyncAction: (id)sender{
    if([contactSync isOn]){
        [[FunambolAPI getInstance]setSync:@"two-way" source: @"addressbook"];
        [[syncWayCell textLabel] setTextColor:[UIColor blackColor]];
        [syncWayLabel setText:NSLocalizedString(@"Two Way", @"Two Way")];
    }else {
        [[FunambolAPI getInstance]setSync:@"none" source: @"addressbook"];
        [[syncWayCell textLabel] setTextColor:[UIColor grayColor]];
        [syncWayLabel setText:NSLocalizedString(@"Disabled", @"Disabled")];
    }
    

}

- (void) companyDirectoryAction: (id)sender {
    if ([companyDirectory isOn])
    {
        if ([remoteURI.text length] < [@"-shared" length] ||
            [
                [remoteURI.text substringFromIndex:
                    ([remoteURI.text length] - ([@"-shared" length]))]
            compare:@"-shared"]
            != 0)
        {
            remoteURI.text = [NSString stringWithFormat:@"%@%@", remoteURI.text, @"-shared"];
        }
    }
    else
    {
        if ([remoteURI.text length] > [@"-shared" length] &&
        [[remoteURI.text substringFromIndex:([remoteURI.text length] - ([@"-shared" length]))] compare:@"-shared"] == 0)
        {
            remoteURI.text = [remoteURI.text substringToIndex:([remoteURI.text length] - ([@"-shared" length]))];
        }
    }
    
    [[FunambolAPI getInstance] setURI:remoteURI.text syncsourcename:@"addressbook"];

}

- (void)viewDidAppear:(BOOL)animated{
    NSString * mode = [[FunambolAPI getInstance] getSync:@"addressbook"];
    if([mode isEqualToString:@"none"]){
        [contactSync setOn:NO animated:YES];
        [[syncWayCell textLabel] setTextColor:[UIColor grayColor]];
    }else{
        [contactSync setOn:YES animated:YES];
        [[syncWayCell textLabel] setTextColor:[UIColor blackColor]];
    }

    if([mode isEqualToString:@"two-way"]){
        [syncWayLabel setText:NSLocalizedString(@"Two Way",@"Two Way")];
    }else if([mode isEqualToString:@"one-way-from-client"]){
        [syncWayLabel setText:NSLocalizedString(@"From Client",@"From Client")];
    }else if([mode isEqualToString:@"one-way-from-server"]){
        [syncWayLabel setText:NSLocalizedString(@"From Server",@"From Server")];
    }else if([mode isEqualToString:@"none"]){
        [syncWayLabel setText:NSLocalizedString(@"Disabled",@"Disabled")];
    }
    [mode release];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
	NSIndexPath *indexPath = [contactsTable indexPathForSelectedRow];
	[contactsTable deselectRowAtIndexPath:indexPath animated:NO];
}

- (void) dealloc {
    [contactsTable release];
    
    [contactSyncCell release];
    [syncWayCell release];
    [remoteURICell release];
    [pathCell release];
    
    [syncValue release];
    [remoteURIValue release];
    
    [contactSync release];
    [remoteURI release];
    [path release];
    [menuList release];
    
    [small_font release];
    
    [funBlue release];
    [syncWayLabel release];
    
    [companyDirectory release];
    [companyDirectoryCell release];
    
    
    [super dealloc];
}

- (void) reload {

}
@end